﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Entities.Admin;
using BLL.Admin;
using System.Collections;

namespace WindowsForms.Admin
{
    public partial class UcNhanVien : UserControl
    {
        int iCellHeight, iHeaderHeight;
        double iTotalWidth;
        bool bNewPage, bFirstPage;
        public StringFormat strFormat;
        public ArrayList arrColumnWidths = new ArrayList();
        public ArrayList arrColumnLefts = new ArrayList();
        public int iCount  ;
        public bool kt = false;
        public bool State = true;
        public int nums = 5;
        public int page = 1;
        public int tong;
        public List<NhanVien> dsnv = new List<NhanVien>();

        public UcNhanVien()
        {
            InitializeComponent();
            datagrviewnv.AutoGenerateColumns = false;
        }

        private void UcNhanVien_Load(object sender, EventArgs e)
        {
            LoadBoPhan();
        }
        private void LoadNhanVien(List<NhanVien> ds)
        {

            DiaChi d = new DiaChi();
            string k = "";
            datagrviewnv.DataSource = ds;

            for (int i = 0; i < datagrviewnv.RowCount; i++)
            {
                string id = datagrviewnv.Rows[i].Cells[1].Value.ToString();
                NhanVien nvv = NhanVien.Objects.GetById(id);
                d = DiaChi.Objects.GetById(nvv.IdDiaChi);
                k = "";
                if (d != null)
                {
                    k += d.SoNha + " " + d.TenDuong + " " + d.QuanHuyen + " " + d.TinhTP;
                    datagrviewnv.Rows[i].Cells[8].Value = k;

                }
                datagrviewnv.Rows[i].Cells[0].Value = i + 1;
            }

            tbdl.TextBox.Text = page + "/ " + tong;

        }
        public List<NhanVien> getPage(int page, List<NhanVien> Ds)
        {
            tong = ManagerForm.TongTrang(Ds.Count, nums);
            var query = from c in Ds
                           .Skip(nums * page - nums).Take(nums)
                        select c;
            return query.ToList();


        }

        private void btrefresh_Click(object sender, EventArgs e)
        {
            kt = true;
            dsnv = NhanVien.Objects.All().ToList();
            LoadNhanVien(getPage(page, dsnv));
        }


        private void dagrnv_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {

            try
            {


                NhanVien nhanvien = new NhanVien();
                DiaChi d = new DiaChi();
                int hang = e.RowIndex;
                string id = datagrviewnv.Rows[hang].Cells[1].Value.ToString();
                if (e.ColumnIndex == 9)
                {
                    nhanvien = NhanVien.Objects.GetById(id);
                    d = DiaChi.Objects.GetById(nhanvien.IdDiaChi);
                    if (QuanLiTaiKhoan.KiemTra(id, TaiKhoan.Objects.All().ToList()))
                    {
                        DialogResult rs = MessageBox.Show("Bạn Thật Sự Muốn Xóa Nhân Viên Này, Trong Quá Trình Xóa Chương Trình Sẻ Thực Hiện Xóa Tất Cả Tài Khoản Do Nhân Viên Này Quản Lí", "Cảnh Báo", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
                        if (rs == DialogResult.Yes)
                            if (rs == DialogResult.Yes)
                            {
                                TaiKhoan.Objects.Delete(p => p.MaNhanVien == id);
                                NhanVien.Objects.Delete(nhanvien);
                                DiaChi.Objects.Delete(d);
                                MessageBox.Show("Successful");

                            }

                    }
                    else
                    {


                        NhanVien.Objects.Delete(nhanvien);
                        DiaChi.Objects.Delete(d);
                        MessageBox.Show("Successful");
                    }


                }

                if (e.ColumnIndex == 10)
                {

                    nhanvien = NhanVien.Objects.GetById(id);
                    DiaChi dc = DiaChi.Objects.GetById(nhanvien.IdDiaChi);
                    FormThemNhanVien fru = new FormThemNhanVien();



                    FormThemNhanVien.dataDc = dc;
                    FormThemNhanVien.dataNv = nhanvien;

                    fru.FormClosed += new FormClosedEventHandler(fru_FormClosed);
                    fru.ShowDialog();






                }
            }
            catch
            {


            }

        }
        void fru_FormClosed(object sender, FormClosedEventArgs e)
        {

            LoadNhanVien(getPage(page, NhanVien.Objects.All().ToList()));
        }
        private void btsapxep_Click(object sender, EventArgs e)
        {
            List<NhanVien> ds;

            if (State)
            {

                ds = QuanLiNhanVien.SapXepTang(getPage(page, NhanVien.Objects.All().ToList()));
                LoadNhanVien(ds);
                State = !State;

            }
            else
            {

                ds = QuanLiNhanVien.SapXepGiam(getPage(page, NhanVien.Objects.All().ToList()));
                LoadNhanVien(ds);
                State = !State;

            }


        }
        public void LoadBoPhan()
        {
            List<BoPhan> ds = BoPhan.Objects.All().ToList();
            foreach (var item in ds)
                cbbbophan.Items.Add(item);
            cbbbophan.DisplayMember = "TenBoPhan";
            cbbbophan.Items.Insert(0, " All ");
            cbbbophan.SelectedIndex = 0;



        }

        private void cbbbophan_Click(object sender, EventArgs e)
        {
            if (cbbbophan.SelectedIndex > 0)
            {
                string mabp = (cbbbophan.SelectedItem as BoPhan).MaBoPhan;
                List<NhanVien> ds = NhanVien.Objects.Find(p => p.MaBoPhan == mabp).ToList();
                LoadNhanVien(getPage(page, ds));

            }
            else if (kt) LoadNhanVien(getPage(page, NhanVien.Objects.All().ToList()));

        }

        private void bttimnv_Click(object sender, EventArgs e)
        {
            string tennv = tbtimnv.TextBox.Text;
            if (!String.IsNullOrWhiteSpace(tennv))
            {
                List<NhanVien> Ds = NhanVien.Objects.Find(p => p.TenNhanVien.Contains(tennv)).ToList();
                LoadNhanVien(getPage(page, Ds));
            }
        }



        private void btntien_Click(object sender, EventArgs e)
        {

            if (page < tong)
                page++;

            if (page <= tong)
            {
                tbdl.TextBox.Text = page + " / " + tong;
                LoadNhanVien(getPage(page, NhanVien.Objects.All().ToList()));

            }
        }

        private void btnlui_Click(object sender, EventArgs e)
        {
            if (page >= 2)
            {
                page--;
                tbdl.TextBox.Text = page + "/ " + tong;

                LoadNhanVien(getPage(page, NhanVien.Objects.All().ToList()));
            }
        }

        private void tbdl_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
                LoadNhanVien(getPage(page, dsnv));
        }
        private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
        {
            int iRow = 0;


            try
            {
                //Set the left margin
                int iLeftMargin = e.MarginBounds.Left;
                //Set the top margin
                int iTopMargin = e.MarginBounds.Top;
                //Whether more pages have to print or not
                bool bMorePagesToPrint = false;
                int iTmpWidth = 0;
                int iCount = 0;

                //For the first page to print set the cell width and header height
                if (bFirstPage)
                {
                    //foreach (DataGridViewColumn GridCol in dataGridViewtk.Columns)
                    //{
                    //    iTmpWidth = (int)(Math.Floor((double)((double)GridCol.Width /
                    //        (double)iTotalWidth * (double)iTotalWidth *
                    //        ((double)e.MarginBounds.Width / (double)iTotalWidth))));

                    //    iHeaderHeight = (int)(e.Graphics.MeasureString(GridCol.HeaderText,
                    //        GridCol.InheritedStyle.Font, iTmpWidth).Height) + 11;

                    //    // Save width and height of headers
                    //    arrColumnLefts.Add(iLeftMargin);
                    //    arrColumnWidths.Add(iTmpWidth);
                    //    iLeftMargin += iTmpWidth;
                    //}
                    for (int k = 0; k < datagrviewnv.ColumnCount - 2; k++)
                    {
                        if (k != 0 & k != 5)
                        {
                             
                                iTmpWidth = (int)(Math.Floor((double)((double)datagrviewnv.Columns[k].Width+15 /
                                (double)iTotalWidth * (double)iTotalWidth *
                                ((double)e.MarginBounds.Width / (double)iTotalWidth))));
                            iTmpWidth = (int)(Math.Floor((double)((double)datagrviewnv.Columns[k].Width /
                                (double)iTotalWidth * (double)iTotalWidth *
                                ((double)e.MarginBounds.Width / (double)iTotalWidth))));

                            iHeaderHeight = (int)(e.Graphics.MeasureString(datagrviewnv.Columns[k].HeaderText,
                                datagrviewnv.Columns[k].InheritedStyle.Font, iTmpWidth).Height) + 11;

                            // Save width and height of headers
                            arrColumnLefts.Add(iLeftMargin);
                            arrColumnWidths.Add(iTmpWidth);
                            iLeftMargin += iTmpWidth;
                        }
                    }
                }

                //Loop till all the grid rows not get printed
                while (iRow <= datagrviewnv.Rows.Count - 1)
                {
                    DataGridViewRow GridRow = datagrviewnv.Rows[iRow];
                    //Set the cell height
                    iCellHeight = GridRow.Height + 10;

                    //Check whether the current page settings allows more rows to print
                    if (iTopMargin + iCellHeight >= e.MarginBounds.Height + e.MarginBounds.Top)
                    {
                        bNewPage = true;
                        bFirstPage = false;
                        bMorePagesToPrint = true;
                        break;
                    }
                    else
                    {
                        if (bNewPage)
                        {
                            //Draw Header
                            e.Graphics.DrawString("Acount Customer",
                                new Font(datagrviewnv.Font, FontStyle.Bold),
                                Brushes.Black, e.MarginBounds.Left,
                                e.MarginBounds.Top - e.Graphics.MeasureString("Acount Customer",
                                new Font(datagrviewnv.Font, FontStyle.Bold),
                                e.MarginBounds.Width).Height - 13);

                            String strDate = DateTime.Now.ToLongDateString() + " " +
                                DateTime.Now.ToShortTimeString();
                            //Draw Date
                            e.Graphics.DrawString(strDate,
                                new Font(datagrviewnv.Font, FontStyle.Bold), Brushes.Black,
                                e.MarginBounds.Left +
                                (e.MarginBounds.Width - e.Graphics.MeasureString(strDate,
                                new Font(datagrviewnv.Font, FontStyle.Bold),
                                e.MarginBounds.Width).Width),
                                e.MarginBounds.Top - e.Graphics.MeasureString("Acount Customer",
                                new Font(new Font(datagrviewnv.Font, FontStyle.Bold),
                                FontStyle.Bold), e.MarginBounds.Width).Height - 13);

                            //Draw Columns                 
                            iTopMargin = e.MarginBounds.Top;
                            //foreach (DataGridViewColumn GridCol in dataGridViewtk.Columns)
                            //{
                            //    e.Graphics.FillRectangle(new SolidBrush(Color.LightGray),
                            //        new Rectangle((int)arrColumnLefts[iCount], iTopMargin,
                            //        (int)arrColumnWidths[iCount], iHeaderHeight));

                            //    e.Graphics.DrawRectangle(Pens.Black,
                            //        new Rectangle((int)arrColumnLefts[iCount], iTopMargin,
                            //        (int)arrColumnWidths[iCount], iHeaderHeight));

                            //    e.Graphics.DrawString(GridCol.HeaderText,
                            //        GridCol.InheritedStyle.Font,
                            //        new SolidBrush(GridCol.InheritedStyle.ForeColor),
                            //        new RectangleF((int)arrColumnLefts[iCount], iTopMargin,
                            //        (int)arrColumnWidths[iCount], iHeaderHeight), strFormat);
                            //    iCount++;
                            //}
                            for (int l = 0; l < datagrviewnv.Columns.Count - 2; l++)
                            {
                                if (l != 0 & l != 5)
                                {
                                    e.Graphics.FillRectangle(new SolidBrush(Color.LightGray),
                                        new Rectangle((int)arrColumnLefts[iCount], iTopMargin,
                                        (int)arrColumnWidths[iCount], iHeaderHeight));

                                    e.Graphics.DrawRectangle(Pens.Black,
                                        new Rectangle((int)arrColumnLefts[iCount], iTopMargin,
                                        (int)arrColumnWidths[iCount], iHeaderHeight));

                                    e.Graphics.DrawString(datagrviewnv.Columns[l].HeaderText,
                                        datagrviewnv.Columns[l].InheritedStyle.Font,
                                        new SolidBrush(datagrviewnv.Columns[l].InheritedStyle.ForeColor),
                                        new RectangleF((int)arrColumnLefts[iCount], iTopMargin,
                                        (int)arrColumnWidths[iCount], iHeaderHeight), strFormat);
                                    iCount++;
                                }
                            }
                            bNewPage = false;
                            iTopMargin += iHeaderHeight;
                        }
                        iCount = 0;
                        //Draw Columns Contents                
                        //foreach (DataGridViewCell Cel in GridRow.Cells)
                        //{
                        //    if (Cel.Value != null)
                        //    {
                        //        e.Graphics.DrawString(Cel.Value.ToString(),
                        //            Cel.InheritedStyle.Font,
                        //            new SolidBrush(Cel.InheritedStyle.ForeColor),
                        //            new RectangleF((int)arrColumnLefts[iCount],
                        //            (float)iTopMargin,
                        //            (int)arrColumnWidths[iCount], (float)iCellHeight),
                        //            strFormat);
                        //    }
                        //    //Drawing Cells Borders 
                        //    e.Graphics.DrawRectangle(Pens.Black,
                        //        new Rectangle((int)arrColumnLefts[iCount], iTopMargin,
                        //        (int)arrColumnWidths[iCount], iCellHeight));
                        //    iCount++;
                        //}
                        for (int t = 0; t < GridRow.Cells.Count - 2; t++)
                        {
                            if (t != 0 & t != 5)
                            {
                                if (GridRow.Cells[t].Value != null)
                                {
                                    e.Graphics.DrawString(GridRow.Cells[t].Value.ToString(),
                                        GridRow.Cells[t].InheritedStyle.Font,
                                        new SolidBrush(GridRow.Cells[t].InheritedStyle.ForeColor),
                                        new RectangleF((int)arrColumnLefts[iCount],
                                        (float)iTopMargin,
                                        (int)arrColumnWidths[iCount], (float)iCellHeight),
                                        strFormat);
                                }
                                //Drawing Cells Borders 
                                e.Graphics.DrawRectangle(Pens.Black,
                                    new Rectangle((int)arrColumnLefts[iCount], iTopMargin,
                                    (int)arrColumnWidths[iCount], iCellHeight));
                                iCount++;
                            }
                        }
                    }

                    iRow++;
                    iTopMargin += iCellHeight;
                }
                //If more lines exist, print another page.
                if (bMorePagesToPrint)
                    e.HasMorePages = true;
                else
                    e.HasMorePages = false;
            }
            catch (Exception exc)
            {
                MessageBox.Show(exc.Message, "Error", MessageBoxButtons.OK,
                   MessageBoxIcon.Error);
            }

        }




        private void printDocument1_BeginPrint(object sender, System.Drawing.Printing.PrintEventArgs e)
        {
            try
            {
                strFormat = new StringFormat();
                strFormat.Alignment = StringAlignment.Near;
                strFormat.LineAlignment = StringAlignment.Center;
                strFormat.Trimming = StringTrimming.EllipsisCharacter;

                arrColumnLefts.Clear();
                arrColumnWidths.Clear();
                iCellHeight = 0;
                iCount = 0;
                bFirstPage = true;
                bNewPage = true;

                // Calculating Total Widths
                iTotalWidth = 0;
                //foreach (DataGridViewColumn dgvGridCol in dataGridViewtk.Columns)
                //{
                //    iTotalWidth += dgvGridCol.Width;
                //}
                for (int k = 0; k < datagrviewnv.Columns.Count - 2; k++)
                {
                    iTotalWidth += datagrviewnv.Columns[k].Width-20;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

        }

        private void btnin_Click(object sender, EventArgs e)
        {

            PrintDialog printDialog = new PrintDialog();
            printDialog.Document = printDocument1;
            printDialog.UseEXDialog = true;


            //Get the document

            if (DialogResult.OK == printDialog.ShowDialog())
            {

                printDocument1.DocumentName = "Test Page Print";
                printDocument1.Print();

            }
        }

    }
}
